package yxy.game.pm2.module.union;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;

import yxy.apple.util.redisson.RedisException;

/** 联盟捐献 */
public class UnionContribution extends UnionModule {
	// bean===========================================================================

	private long progress;// 进度
	private DateTime updateTime;// 每日刷新时间

	public long getProgress() {
		return progress;
	}

	public void setProgress(long progress) {
		this.progress = progress;
	}

	public DateTime getUpdateTime() {
		return updateTime;
	}

	public void setUpdateTime(DateTime updateTime) {
		this.updateTime = updateTime;
	}

	// func==========================================================================
	public void update() {
		DateTime now = DateTime.now();
		if (getUpdateTime() == null || !new LocalDate(now).equals(new LocalDate(getUpdateTime()))) {
			setUpdateTime(now);
			setProgress(0);
			this.set();
		}
	}

	// redis==========================================================================

	static private String key(String unionCode) {
		return String.format("UNION:%s:MODULE:CONTRIB", unionCode);
	}

	public void set() {
		try {
			setv(key(getUnionCode()), this);
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	static public UnionContribution get(UnionBean union) {
		try {
			UnionContribution module = getv(key(union.getCode()));
			if (module == null) {
				module = create(union);
			}
			module.update();
			return module;
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static UnionContribution create(UnionBean union) {
		UnionContribution module = new UnionContribution();
		module.setUnionCode(union.getCode());
		module.set();
		return module;
	}

	static public enum ContributeType {
		NONE(0), //
		COIN(1), // 钱币捐献
		GOLD(2), // 元宝捐献
		RICH(3), // 土豪随意
		;

		private int number;

		private ContributeType(int number) {
			this.number = number;
		}

		public int getNumber() {
			return number;
		}

		static public ContributeType forNumber(int number) {
			switch (number) {
			case 1:
				return COIN;
			case 2:
				return GOLD;
			case 3:
				return RICH;
			default:
				return NONE;
			}
		}
	}

	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key(getUnionCode()));
	}
	
	@Override
	public boolean tryLock() throws InterruptedException {
		return super.tryLock();
	}
}
